package Action;

import Service.UpdateInfoService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import java.util.Map;

public class TagAction extends ActionSupport
{
    private String user_name;
    private String selectCount = "0";  //选择标签的个数
    private UpdateInfoService updateInfoService;
    private String page = "0";
    private int limit = 15;
    private String [] tagsForShow;  //本次用于显示的标签的列表
    private String tag_register = "0";  //若为0则表示是重新选择标签页面过来的；若为1则表示是注册的选择标签页面过来的

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getSelectCount() {
        return selectCount;
    }

    public void setSelectCount(String selectCount) {
        this.selectCount = selectCount;
    }

    public UpdateInfoService getUpdateInfoService() {
        return updateInfoService;
    }

    public void setUpdateInfoService(UpdateInfoService updateInfoService) {
        this.updateInfoService = updateInfoService;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public String[] getTagsForShow() {
        return tagsForShow;
    }

    public void setTagsForShow(String[] tagsForShow) {
        this.tagsForShow = tagsForShow;
    }

    public String getTag_register() {
        return tag_register;
    }

    public void setTag_register(String tag_register) {
        this.tag_register = tag_register;
    }

    public String execute()
    {
        String param_page = ServletActionContext.getRequest().getParameter("page");
        setPage(param_page != null ? param_page : "0");
        Map<String, Object> session =  (Map<String, Object>) ActionContext.getContext().getSession();
        String user_name = (String) session.get("user_name");  //获取登录或注册时存入session的参数——用户名

        String[] tagNames = updateInfoService.getTags();
        int index = Integer.parseInt(page);
        int start = index * limit;
        int end = start + limit - 1;

        tagsForShow = subArray(tagNames,start,end);
        session.put("tags",tagsForShow);
        if(tagsForShow.length > 0) {
            if (index > 0)
                return "append";
            else
                return "success";
        }
        else
            return "fail";
    }

    private String[] subArray(String[] array,int start,int end)
    {
        if (start >= array.length) {
            String [] shit = new String[1];
            shit[0] = "NO_MORE";
            return shit;
        }
        String [] res = new String [end-start+1];
        for (int i = start;i<=end;i++){
            res[i-start] = array[i];
        }
        return res;

    }

}
